package com.example.cardemo

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.example.cardemo.adapter.NewsAdapter
import com.example.cardemo.bean.NewslistBean
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class TabNewsFragment : Fragment() {

    private var url: String = "http://v.juhe.cn/toutiao/index?key=b215755cd0ad438888aae53764b3fa3e&type="
    private lateinit var rootView: View
    private var title: String? = null
    private lateinit var recyclerView: RecyclerView
    private lateinit var mNewsAdapter: NewsAdapter

    private val mHandler = Handler(Looper.getMainLooper()) { msg ->
        if (msg.what == 100) {
            val data = msg.obj as String
            Log.d("TabNewsFragment", "Received JSON: $data")
            val newslistBean = Gson().fromJson(data, NewslistBean::class.java)
            Log.d("TabNewsFragment", "Parsed NewslistBean: $newslistBean")
            if (newslistBean != null && newslistBean.result != null && newslistBean.result.data != null) {
                // 获取 result.data 列表
                val resultList = newslistBean.result.data
                mNewsAdapter.setListData(resultList)
            } else {
                Toast.makeText(context, "获取失败，原因是： ${msg.obj}", Toast.LENGTH_SHORT).show()
            }
        }
        true
    }

    companion object {
        private const val ARG_PARAM = "title"

        @JvmStatic
        fun newInstance(param: String) = TabNewsFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_PARAM, param)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            title = it.getString(ARG_PARAM)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_tab_news, container, false)

        // 初始化控件
        recyclerView = rootView.findViewById(R.id.recycler_view)
        return rootView
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mNewsAdapter = NewsAdapter()
        recyclerView.adapter = mNewsAdapter

        mNewsAdapter.setOnItemClickListener(object : NewsAdapter.OnItemClickListener {
            override fun onItemClick(data: NewslistBean.NewslistData, position: Int) {
                // 详情页跳转
                val intent = Intent(activity, NewsDetailsActivity::class.java)
                intent.putExtra("data", data)
                startActivity(intent)
            }
        })

        getData()
    }

    // 获取数据
    private fun getData() {
        val okHttpClient = OkHttpClient()
        val request = Request.Builder().url(url + title).get().build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val message = Message()
                message.what = 100
                message.obj = response.body()?.string()
                mHandler.sendMessage(message)
            }

            override fun onFailure(call: Call, e: IOException) {
                Log.d("TabNewsFragment", "onFailure: ${e.message}")
                activity?.runOnUiThread {
                    Toast.makeText(context, "获取失败，原因是： ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        })
    }
}